﻿using Microsoft.AspNetCore.Mvc;
using Qy.Common;
using Qy.Models;
using Qy.Service;
using Qy.Web.Authorize;
using System.Threading.Tasks;

namespace Qy.Web.Api
{
    [Route("Api/[controller]/[action]")]
    public class LoginController : Controller
    {
        private readonly UserService _adminUserService;
        private readonly LoginUtil _LoginUtil;
        private readonly LogLoginService _logLoginService;
        private readonly ConfigService _configService;
        private readonly NoticeKeyService _noticeKey;
        public LoginController(LoginUtil LoginUtil, UserService adminUserService, LogLoginService logLoginService, ConfigService configService, NoticeKeyService noticeKey)
        {
            _LoginUtil = LoginUtil;
            _adminUserService = adminUserService;
            _logLoginService = logLoginService;
            _configService = configService;
            _noticeKey = noticeKey;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login([FromBody] LoginDto dto)
        {
            string ip = HttpContextExtension.GetClientUserIp(HttpContext);
            if (dto.Username == null || dto.Password == null)
                return Json(new { status = 0, msg = "用户名密码不能为空！" });
            User loginInfo = await _adminUserService.CheckUorP(dto.Username, dto.Password);
            if (loginInfo != null)
            {
                TokenModelJwt jwtSettings = new();
                AppSettings.Bind("Jwt", jwtSettings);

                if(dto.Remember)
                    jwtSettings.Expires = 60 * 30; //DateTime.Now.AddSeconds(),
                else
                    jwtSettings.Expires = 30;

                jwtSettings.UserName = loginInfo.Username;
                jwtSettings.UserId = loginInfo.Id;
                jwtSettings.UserGid = loginInfo.Gid;
                
                string token = JwtHelper.CreateJwt(jwtSettings);
                //更新数据库用户登录状态
                _adminUserService.UpdateLoginInfoAsync(loginInfo.Id, ip);
                //登录日志单独写入
                await _logLoginService.InsertLogLoginAsync(loginInfo.Id, ip);
                return Json(new { status = 1, msg = "登录成功！", token });
            }
            else
                return Json(new { status = 0, msg = "用户名密码错误！" });
        }


        [Verify]
        [HttpGet]
        public async Task<IActionResult> GetUserInfo()
        {
            UserInfo userInfo = await _LoginUtil.UserInfoAsync();
            SytemConfig sytemConfig = await _configService.GetSytemConfigAsync();
            ViewStatistics statistics = new()
            {
                NoticeNoRead = await _noticeKey.CountAsync(userInfo.UserId)//统计消息未读
            };
            return Json(new { status = 1, data = userInfo , sytemConfig , statistics });
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult LoginOut()
        {
            //await HttpContext.SignOutAsync(JwtBearerDefaults.AuthenticationScheme);
            return Json(new { status = 1, msg = "成功退出" });
        }

    }
}
